package com.example.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * Redis配置类
 */
@Configuration
public class RedisConfig {

    /**
     * 配置RedisTemplate以支持自定义序列化方式
     *
     * @param factory Redis连接工厂，用于创建和管理Redis连接
     * @return 配置好的RedisTemplate实例，用于操作Redis
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置键的序列化方式为StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        // 设置值的序列化方式为GenericJackson2JsonRedisSerializer，用于JSON序列化
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 设置哈希键的序列化方式为StringRedisSerializer
        template.setHashKeySerializer(new StringRedisSerializer());
        // 设置哈希值的序列化方式为GenericJackson2JsonRedisSerializer，用于JSON序列化
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 初始化RedisTemplate
        template.afterPropertiesSet();
        return template;
    }
}
